<?php

namespace app\bll;

use app\validate\MsgChannel as ValidateMsgChannel;
use core\lib\paginator\RcPaginator;
use Exception;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use support\Db;

/**
 * 消息通道
 */
class MsgChannel
{

    /**
     * 查找
     *
     * @param integer $id
     * @return array
     */
    public function find(int $id): array
    {
        $data =  Db::table('frame_msg_channel')
            ->where('id', '=', $id)
            ->first();
        return $data === null ? [] : get_object_vars($data);
    }

    /**
     *添加
     *
     * @param array $data
     * @return integer
     */
    public function add(array $data): int
    {
        $ValidateMsgChannel = new ValidateMsgChannel();
        if (!$ValidateMsgChannel->check($data)) {
            throw new Exception($ValidateMsgChannel->getSimpleError());
        }

        list($extendid, $methodid) =  explode('_', $data['extend']);
        $bllComponentExtend = new ComponentExtend();
        $extendinfo = $bllComponentExtend->find($extendid);

        $bllComponentExtendMethod = new ComponentExtendMethod();
        $methodinfo              = $bllComponentExtendMethod->find($methodid);

        $data['extend']   = $extendinfo['ident'] . '/' . $methodinfo['path'];
        $data['extendid'] = $extendid;
        $data['methodid'] = $methodid;
        return  Db::table('frame_msg_channel')
            ->insertGetId($data);
    }

    /**
     * 编辑
     *
     * @param integer $id
     * @param array $data
     * @return integer
     */
    public function edit(int $id, array $data): int
    {
        $ValidateMsgChannel = new ValidateMsgChannel();
        if (!$ValidateMsgChannel->check($data)) {
            throw new Exception($ValidateMsgChannel->getSimpleError());
        }

        list($extendid, $methodid) = explode('_', $data['extend']);
        $bllComponentExtend         = new ComponentExtend();
        $extendinfo                 = $bllComponentExtend->find($extendid);

        $bllComponentExtendMethod = new ComponentExtendMethod();
        $methodinfo              = $bllComponentExtendMethod->find($methodid);

        $data['extend']   = $extendinfo['ident'] . '/' . $methodinfo['path'];
        $data['extendid'] = $extendid;
        $data['methodid'] = $methodid;

        return  Db::table('frame_msg_channel')
            ->where('id', '=', $id)
            ->update($data);
    }


    /**
     * 删除
     *
     * @param integer|string|array $id
     * @return void
     */
    public function delete(int|string|array $id)
    {

        Db::beginTransaction();
        try {
            if (is_int($id)) {
                $id = [$id];
            }
            if (is_string($id)) {
                $id = explode(',', $id);
            }

            $bllMsgTemplate = new MsgTemplate();
            foreach ($id as $_id) {
                $templates = $bllMsgTemplate->selectByChannelid($_id);
                foreach ($templates as $template) {
                    $tempchannel = str_replace(',' . $_id . ',', '', $template['channel']);
                    if (!$tempchannel) {
                        //删除
                        $bllMsgTemplate->delete($template['id']);
                    } else {
                        //编辑
                        $bllMsgTemplate->edit($template['id'], ['channel' => $tempchannel]);
                    }
                }
            }

            Db::table('frame_msg_channel')
                ->whereIn('id',  $id)
                ->delete();
            Db::commit();
        } catch (Exception $ex) {
            Db::rollBack();
            throw $ex;
        }
    }

    /**
     * 查询所有通道
     *
     * @return array
     */
    public function select(): array
    {
        return  Db::table('frame_msg_channel')->get()
            ->map(function ($value) {
                return (array)$value;
            })
            ->toArray();
    }

    /**
     * 分页查询
     *
     * @param integer $pagesize
     * @return LengthAwarePaginator
     */
    public function paginate(int $pagesize = 20): LengthAwarePaginator
    {

        //获取所有扩展
        $bllComponentExtend = new ComponentExtend();
        $extends            = $bllComponentExtend->cascader(isjson: false);
        $extends            = array_column($extends, null, 'ident');

        $channels =  Db::table('frame_msg_channel')
            ->orderBy('id', 'desc')
            ->paginate(
                perPage: $pagesize
            );

        foreach ($channels as $key => $channel) {
            list($extendident, $extendclass, $extendmethor) = explode('/', $channel->extend);
            $channels[$key]->extendtitle = isset($extends[$extendident]) ? $extends[$extendident]['title'] : '';

            if (isset($extends[$extendident]) && $extends[$extendident]['children']) {
                $methods = $extends[$extendident]['children'];
                $methods = array_column($methods, null, 'path');
                if (isset($methods[$extendclass . '/' . $extendmethor])) {
                    $channels[$key]->extendtitle .= ' / ' . $methods[$extendclass . '/' . $extendmethor]['title'];
                }
            }
        }
        return $channels;
    }
}
